package com.shuimutong.gmq.server.dao.impl;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

import com.shuimutong.gmq.server.bean.dos.MessageDo;
import com.shuimutong.gmq.server.dao.MessageDao;
import com.shuimutong.gmq.server.exception.DaoException;
import com.shuimutong.gmvc.annotation.XRepository;
import com.shuimutong.guti.bean.TwoTuple;
import com.shuimutong.gutil.common.GUtilCommonUtil;

@XRepository
public class MessageDaoImpl extends BaseDao<MessageDo, Long> implements MessageDao {
	
	@Override
	public void saveMessage(String topic, String body) throws DaoException {
		String sql = "insert into gmq_message(topic, message_body) values(?,?);";
		Object[] params = {topic, body};
		try {
			super.getSqlExecutor().insert(sql, params);
		} catch (Exception e) {
			throw new DaoException(e);
		}
	}
	
	@Override
	public List<TwoTuple<Long, String>> listMessage(String topic, long offset, int size) throws DaoException {
		List<TwoTuple<Long, String>> list = new ArrayList();
		String sql = "select id, message_body from gmq_message where topic=? and id>? order by id limit ?";
		Object[] params = {topic, offset, size};
		try {
			List<Object[]> objList = super.getSqlExecutor().query(sql, params);
			if(!GUtilCommonUtil.checkListEmpty(objList)) {
				for(Object[] objs : objList) {
					if(!GUtilCommonUtil.checkListEmpty(objs)) {
						long id = ((BigInteger)objs[0]).longValue();
						String msg = (String)objs[1];
						list.add(new TwoTuple<Long, String>(id, msg));
					}
				}
			}
		} catch (Exception e) {
			throw new DaoException(e);
		}
		return list;
	}

}
